<?php

namespace App\Model;


use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;

class Union extends BaseModel
{
    const UNION_TRIE_TREE_CACHE_TREE = 'cms:admin:unionList:trieTree';//工会trie树cache的key

    protected $table = 'union';
    protected $user_table = 'union_user';
    protected $room_table = 'union_room';
    protected $sign_table = 'union_signing';
    public $timestamps = false;
    protected $connection = 'api';
    protected $union_param = 'union_param';
    protected $union_deposit_log = 'union_deposit_log';
    protected $union_shop = 'union_shop';


    public function getList($input = [])
    {
        $limit = $input['limit'] ?? 10;
        $page = $input['page'] ?? 1;
        $uuid = $input['uuid'] ?? '';
        $name = $input['name'] ?? '';
        $user_uuid = $input['user_uuid'] ?? '';
        $reward_type = empty($input['reward_type']) ? 0 : $input['reward_type'];
        $where = [];
        if ($input['status'] > -1) {
            $where['union.authentication_status'] = $input['status'];
        }
        if ($uuid) {
            $where['union.uuid'] = $uuid;
        }
        if ($name) {
//            $where['union.name'] = $name;
            $where[] = ['union.name', 'like', '%' . $name . '%'];
        }
        if ($user_uuid) {
            $where['user.uuid'] = $user_uuid;
        }
        if ($reward_type > -1) {
            $where['union.reward_type'] = $reward_type;
        }
        $data = DB::connection('api')->table($this->table)
            ->leftJoin('user', 'user.user_id', '=', $this->table . '.un_user_id')
            ->where($where)
            ->select($this->table . '.*', 'nickname', 'user.uuid as user_uuid')
            ->orderBy('id', 'desc')
            ->get();
        $total = count($data);
        $res['data'] = $this->objToArray(collect($data)->forPage($page, $limit)->values()->toArray());
        foreach ($res['data'] as &$v) {
            $v['portrait'] = build_image($v['portrait']);
        }
        $res['total'] = $total;
        return $res;
    }

    public function getUnionInfo($user_id)
    {
        $res = DB::connection($this->connection)->table($this->table)->where(['un_user_id' => $user_id])->first();
        return $this->objToArray($res);
    }

    public function getUserUnionInfo($user_id)
    {
        $res = DB::connection($this->connection)->table($this->user_table)->where(['user_id' => $user_id])->first();
        return $this->objToArray($res);
    }


    public function getUnionRooms($union_id)
    {

        $where['union.id'] = $union_id;
        $data = DB::connection('api')->table($this->table)
            ->leftJoin('room', 'room.user_id', '=', $this->table . '.un_user_id')
            ->leftJoin($this->room_table, $this->room_table . '.room_id', '=', 'room.room_id')
            ->where($where)
            ->select($this->table . '.*', 'room.user_id as room_user_id', 'business_type', 'room.room_id', 'room.name as room_name', 'room.room_type', 'room_uid', $this->room_table . '.id as room_join_id')
            ->get();
        return $this->objToArray($data);
    }

    //用户
    public function getUnionUser($input)
    {
        $page = $input['page'] ?? 1;
        $limit = $input['limit'] ?? 10;
        $where['un_id'] = $input['id'];
        $data = DB::connection('api')->table($this->user_table)
            ->leftJoin('user', 'user.user_id', '=', $this->user_table . '.user_id')
            ->select($this->user_table . '.*', 'nickname', 'user.uuid as user_uuid')
            ->where($where)->orderBy($this->user_table . '.id', 'asc')->get();
        $total = count($data);
        $res['data'] = $this->objToArray(collect($data)->forPage($page, $limit)->values()->toArray());
        $res['total'] = $total;
        return $res;
    }

    /*
     * 更新
     * */
    public function updateUnion($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/union/updateUnion', $data, 'json', 'POST');
    }


    public function getSigning($input)
    {
        $where['un_id'] = $input['id'] ?? 0;
        $page = $input['page'] ?? 1;
        $limit = $input['limit'] ?? 10;
        if (isset($input['uuid'])){
            $where['uuid'] = $input['uuid'];
        }
        $res = DB::connection('api')->table($this->sign_table)
            ->leftJoin('user', 'user.user_id', '=', $this->sign_table . '.user_id')
            ->select($this->sign_table . '.*', 'nickname', 'user.uuid as user_uuid')
            ->where($where)->paginate($limit, '*', 'page', $page);
        return $this->objToArray($res);
    }


    /**
     * 获取公会权限配置表数据
     */
    public function getUnionParam()
    {
        $result = DB::connection('api')->table($this->union_param)->get()->toArray();
        return $result;
    }


    public function createUnionParam($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/union/createUnionParam', $data, 'urlencoded', 'GET');
    }

    //获取财富等级与活跃等级
    public function getGrade($unionId)
    {
        $res = curl_request(getKkaudioApiUrl() . '/inner/union/getGrade', ['id' => $unionId], 'urlencoded', 'GET');
        return $res['data'];
    }

    public function getUnionParamList($unionId)
    {
        $where['union_id'] = $unionId;
        $result = DB::connection('api')->table($this->union_param)->where($where)->first();
        if (empty($result)) {
            return [];
        }
        return self::objToArray($result);
    }

    public function updateUnionParam($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/union/updateUnionParam', $data, 'urlencoded', 'POST');
    }

    public function getUnionDepositList($request)
    {
        $limit = $request->input('limit', 10);
        $page = $request->input('page', 1);
        $uuid = $request->input('uuid', '');
        $userUid = $request->input('user_uuid', '');
        $orderType = $request->input('type', 0);
        $orderStatus = $request->input('status', -1);
        $startTime = $request->input('begin_date', '');
        $endTime = $request->input('end_date', '');
        $where = '';
        if ($orderType > 0) {
            $where .= " a.type = '{$orderType}'";
        }
        if ($orderStatus > -1) {
            if ($where) {
                $where .= " AND a.status = '{$orderStatus}'";
            } else {
                $where .= " a.status = '{$orderStatus}'";
            }
        }
        if ($startTime && empty($endTime)) {
            $startTime = $startTime . " 00:00:00";
            if ($where) {
                $where .= " AND a.created_time >= '{$startTime}'";
            } else {
                $where .= " a.created_time >= '{$startTime}'";
            }
        }
        if ($endTime && empty($startTime)) {
            $endTime = $endTime . " 23:59:59";
            if ($where) {
                $where .= " AND a.created_time <= '{$endTime}'";
            } else {
                $where .= " a.created_time <= '{$endTime}'";
            }
        }
        if ($startTime && $endTime) {
            $startTime = $startTime . " 00:00:00";
            $endTime = $endTime . " 23:59:59";
            if ($where) {
                $where .= " AND a.created_time BETWEEN '{$startTime}' AND '{$endTime}'";
            } else {
                $where .= " a.created_time BETWEEN '{$startTime}' AND '{$endTime}'";
            }
        }
        if ($uuid) {
            if ($where) {
                $where .= " AND b.uuid = '{$uuid}'";
            } else {
                $where .= " b.uuid = '{$uuid}'";
            }
        }
        if ($userUid) {
            if ($where) {
                $where .= " AND c.uuid = '{$userUid}'";
            } else {
                $where .= " c.uuid = '{$userUid}'";
            }
        }
        // 获取总数
        $totalSql = "SELECT a.id FROM zb_union_deposit_log a Left JOIN zb_union b ON a.union_id = b.id LEFT JOIN zb_user c ON a.user_id = c.user_id";
        if ($where) {
            $totalSql = $totalSql . " WHERE " . $where;
        }
        $totalSql = "SElECT COUNT(*) AS total FROM (" . $totalSql . ") t";
        $total = DB::connection('api')->selectOne($totalSql);

        // 分页获取数据
        $sql = "SELECT a.*, b.name, c.uuid, c.nickname FROM zb_union_deposit_log a Left JOIN zb_union b ON a.union_id = b.id LEFT JOIN zb_user c ON a.user_id = c.user_id";
        if ($where) {
            $sql = $sql . " WHERE " . $where;
        }
        $sql = $sql . " ORDER BY a.created_time desc LIMIT " . (($page - 1) * $limit) . ", {$limit}";

        $list = DB::connection('api')->select($sql);
        return ['data' => $list, 'total' => $total->total];
    }


    public function recallPayment($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/union/cmsRecallDrawDeposit', $data, 'urlencoded', 'POST');
    }


    public function getUnionMallList($input)
    {
        $limit = $input['limit'] ?? 10;
        $page = $input['page'] ?? 1;
        $status = $input['status'];
        $level = $input['level'];
        $startTime = $input['begin_date'] ?? '';
        $endTime = $input['end_date'] ?? '';

        $where = '';
        if ($status > -1) {
            $where .= " status = '{$status}'";
        }
        if ($level > -1) {
            if ($where) {
                $where .= " AND active_level = '{$level}'";
            } else {
                $where .= " active_level = '{$level}'";
            }
        }
        if ($startTime && empty($endTime)) {
            $startTime = $startTime . " 00:00:00";
            if ($where) {
                $where .= " AND created_time >= '{$startTime}'";
            } else {
                $where .= " created_time >= '{$startTime}'";
            }
        }
        if ($endTime && empty($startTime)) {
            $endTime = $endTime . " 23:59:59";
            if ($where) {
                $where .= " AND created_time <= '{$endTime}'";
            } else {
                $where .= " created_time <= '{$endTime}'";
            }
        }
        if ($startTime && $endTime) {
            $startTime = $startTime . " 00:00:00";
            $endTime = $endTime . " 23:59:59";
            if ($where) {
                $where .= " AND created_time BETWEEN '{$startTime}' AND '{$endTime}'";
            } else {
                $where .= " created_time BETWEEN '{$startTime}' AND '{$endTime}'";
            }
        }

        // 获取总数
        $totalSql = "SELECT id FROM zb_union_shop";
        if ($where) {
            $totalSql = $totalSql . " WHERE " . $where;
        }
        $totalSql = "SElECT COUNT(*) AS total FROM (" . $totalSql . ") t";
        $total = DB::connection('api')->selectOne($totalSql);

        // 分页获取数据
        $sql = "SELECT * FROM zb_union_shop";
        if ($where) {
            $sql = $sql . " WHERE " . $where;
        }
        $sql = $sql . " ORDER BY created_time desc LIMIT " . (($page - 1) * $limit) . ", {$limit}";

        $list = DB::connection('api')->select($sql);
        return ['data' => $list, 'total' => $total->total];
    }


    public function deletePropItem($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/union/deletePropItem', $data, 'urlencoded', 'POST');
    }

    public function createUnionShopItem($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/union/add_shop', $data, 'urlencoded', 'POST');
    }

    public function updateUnionShopItem($data)
    {
        return curl_request(getKkaudioApiUrl() . '/inner/union/add_shop', $data, 'urlencoded', 'POST');
    }

    public function getUnionByUnIds($un_ids)
    {
        return DB::connection('api')->table($this->table)->whereIn('id', $un_ids)->get(['id', 'name'])->toArray();
    }

    public function getUnionList()
    {
        return DB::connection('api')->table($this->table)->get(['id', 'name']);
    }

    /**
     * 获取公会名字
     * @return \Illuminate\Support\Collection
     */
    public function getAllUnionNames()
    {
        return DB::connection('api')->table($this->table)->where('id', '>', 0)
            ->get(['id', 'name']);
    }

    /**
     * 将工会数据格式化为Trie树
     * @return bool
     */
    public function createTrieTree()
    {
        try {
            //获取所有的公会
            $unionList = $this->getAllUnionNames();
            if (!$unionList->count()) {
                return true;
            }

            //构建Trie树
            $tree = new \App\Libs\TrieTree();
            foreach ($unionList as $item) {
                $tree->addWords(strval($item->id), strval($item->name));
            }

            $targetJson = json_encode($tree->getTargetArray(), JSON_UNESCAPED_UNICODE);
            $cacheKey = self::UNION_TRIE_TREE_CACHE_TREE;
            Cache::forget($cacheKey);//先清除缓存
            Cache::put($cacheKey, $targetJson, now()->addDays(7));//存入缓存
            return true;
        } catch (\Throwable $exception) {
            return false;
        }
    }

    /**
     * 获取Trie树
     * @return string
     */
    public function getUnionTrieTree(): string
    {
        $cacheKey = self::UNION_TRIE_TREE_CACHE_TREE;
        $cache = Cache::get($cacheKey);
        if ($cache) {
            return strval($cache);
        }

        $this->createTrieTree();
        return strval(Cache::get($cacheKey));
    }

    /**
     * 根据name获取公会列表
     * @param string $name
     * @return array|\Exception
     */
    public function getUnionsByName(string $name)
    {
        try {
            $tree = new \App\Libs\TrieTree();
            $tree->setTargetArray($this->getUnionTrieTree());
            return $tree->getAllMatches($name);
        } catch (\Throwable $exception) {//发生异常
            Log::error('getUnionsByName' . $exception->getMessage());//记录一下日志
            return new \Exception('发生错误，公会获取失败');
        }
    }

    //根据用户ID获取公会信息
    public function getUnionInfoByUserIds($userIds)
    {
        $list = DB::connection($this->connection)->table($this->user_table)
            ->whereIn('user_id', $userIds)
            ->select(['un_id', 'user_id'])
            ->get();
        $list = $this->objToArray($list);
        $res = [];
        if(!empty($list)) {
            $unionIds = array_column($list ,'un_id');
            $unionList = DB::connection($this->connection)->table($this->table)
                ->whereIn('id', $unionIds)
                ->select(['id', 'name'])
                ->get();
            $unionList = array_column($this->objToArray($unionList), null, 'id');

            foreach($list as $val) {
                $res[$val['user_id']] = [
                    'user_id' => $val['user_id'],
                    'union_id' => $val['un_id'],
                    'union_name' => empty($unionList[$val['un_id']]['name']) ? '' : $unionList[$val['un_id']]['name'],
                ];
            }
        }

        return $res;
    }

    //设置公会奖励类型
    public function unionSetRewardType($data){
        $res = curl_request(getKkaudioApiUrl() . '/inner/unionSetRewardType', $data, 'json', 'POST');
        return curlResultHandle($res);
    }



}
